#include "homepage.h"
#include "ui_homepage.h"
#include "globalval.h"

HomePage::HomePage(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::HomePage)
{
    ui->setupUi(this);

    //实例化界面
    setWig = new SetWig;
    stm32Wig = new Stm32Wig;
    deviceSearch = new DeviceSearch;


    //将界面依次添加到堆栈窗体
    ui->stackedWidget->addWidget(stm32Wig);
    ui->stackedWidget->addWidget(setWig);
    ui->stackedWidget->addWidget(deviceSearch);


    //连接列表界面和堆栈窗体的信号
    QObject::connect(ui->listWidget, SIGNAL(currentRowChanged(int)),
                     ui->stackedWidget, SLOT(setCurrentIndex(int)));

    connect(ui->pushButton, &QPushButton::clicked,
            this, &HomePage::onConnectButtonClicked);
}

HomePage::~HomePage()
{
    delete ui;
}

void HomePage::onConnectButtonClicked()
{
    QString ipAddress = ui->lineEdit->text(); // 从QLineEdit获取IP地址
    qDebug()<<ipAddress;
    if(!ipAddress.isEmpty())
    {
         mqtt = new MqttHandler;

         GlobalVal::mqtt = mqtt;
         mqtt->setHost(QHostAddress(ipAddress));
         mqtt->setPort(1883);
         mqtt->connectToHost();
         connect(mqtt, &MqttHandler::dataUpSignal, stm32Wig, &Stm32Wig::onDataUp);
    }
    else
    {
        // 处理错误，例如显示一个消息框告知用户输入IP地址
         QMessageBox::warning(this, "IP地址缺失", "请输入MQTT服务器的IP地址。");
    }
}
